<template>
  <t-dialog
    :header="header"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    @confirm="onSubmit"
    :confirmBtn="{
      content: loading ? '提交中...' : '确认',
      theme: 'primary',
      loading: loading,
    }"
    width="60%"
    top="5%"
  >
    <t-form ref="form" :data="formData" labelWidth="150px" :rules="rules">
      <t-row style="row-gap: 24px">
        <t-col :span="12">
          <t-form-item label="分组名" name="name">
            <t-input style="width: 390px" v-model="formData.name" placeholder="请输入内容"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="分组类型">
            <t-radio-group style="width: 390px" v-model="formData.reviewMenuType">
              <t-radio value="1"> 菜单</t-radio>
              <t-radio value="2"> 评审组</t-radio>
            </t-radio-group>
          </t-form-item>
        </t-col>
        <t-col v-if="['2'].includes(formData.reviewMenuType)" :span="12">
          <t-form-item label="学科分类" name="subjectClassification">
            <t-select
              multiple
              style="width: 390px"
              placeholder="学科分类"
              clearable
              :options="dict.type.subject_classification"
              v-model="formData.subjectClassification"
            >
            </t-select>
          </t-form-item>
        </t-col>
        <t-col v-if="['2'].includes(formData.reviewMenuType)" :span="12">
          <t-form-item label="评审业务类型" name="reviewType">
            <t-select
              style="width: 390px"
              placeholder="评审业务类型"
              clearable
              :options="dict.type.review_type"
              v-model="formData.reviewType"
            >
            </t-select>
          </t-form-item>
        </t-col>
        <t-col v-if="['1'].includes(formData.reviewType) && ['2'].includes(formData.reviewMenuType)" :span="12">
          <t-form-item label="评审指标体系" name="indexId">
            <t-select
              style="width: 390px"
              placeholder="评审指标体系"
              clearable
              :options="dataOptions"
              v-model="formData.indexId"
            >
            </t-select>
            <t-button
              v-if="formData.indexId"
              @click="
                dialog.header = '评审指标体系详情';
                dialog.objId = formData.indexId;
                dialog.open = true;
              "
              variant="text"
              class="t-button-link"
            >
              <t-icon name="info-circle" slot="icon" />
              详情
            </t-button>
          </t-form-item>
        </t-col>
        <t-col v-if="['2'].includes(formData.reviewMenuType)" :span="12">
          <t-form-item label="专家评审开始时间" name="startReviewDate">
            <t-date-picker
              allow-input
              clearable
              style="width: 390px"
              v-model="formData.startReviewDate"
            ></t-date-picker>
          </t-form-item>
        </t-col>
        <t-col v-if="['2'].includes(formData.reviewMenuType)" :span="12">
          <t-form-item label="评审会议时间" name="reviewMeetingDate">
            <t-date-picker
              allow-input
              clearable
              style="width: 390px"
              v-model="formData.reviewMeetingDate"
            ></t-date-picker
            ><br />
          </t-form-item>
          <p style="color: red; margin-left: 15%">如果是现场评审请设置当天的评审会议时间，便于申报用户后续修改。</p>
        </t-col>
        <t-col v-if="['2'].includes(formData.reviewMenuType)" :span="12">
          <t-form-item label="专家评审截止时间" name="endReviewDate">
            <t-date-picker allow-input clearable style="width: 390px" v-model="formData.endReviewDate"></t-date-picker>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="序号" name="sort">
            <t-input-number
              style="width: 390px"
              clearable
              v-model="formData.sort"
              :min="1"
              placeholder="请输入"
            ></t-input-number>
          </t-form-item>
        </t-col>

        <t-col :span="12">
          <t-form-item label="附件上传" name="sysAttMainIds">
            <file-upload
              tips=""
              :fileList="fileLists"
              moduleKey="lockModuleKey"
              v-model="formData.sysAttMainVo.sysAttMainIds"
              :multiple="true"
            ></file-upload>
          </t-form-item>
          <!-- <t-form-item label="分组说明" name="note">
            <t-textarea  :autosize="{minRows: 5}" v-model="formData.note"></t-textarea>
          </t-form-item> -->
        </t-col>
      </t-row>
    </t-form>
    <add-edit-review-standard
      :editOpen="false"
      :objId="dialog.objId"
      :visible.sync="dialog.open"
      v-if="dialog.open"
    ></add-edit-review-standard>
  </t-dialog>
</template>

<script>
import AddEditReviewStandard from './add-edit-review-standard.vue';
import FileUpload from '@/components/FileUpload/index.vue';
import { getFiles } from '@/api/common';
import Vue from 'vue';

export default {
  name: 'add-edit-group',
  dicts: ['review_type', 'subject_classification'],
  components: {
    AddEditReviewStandard,
    FileUpload,
  },
  props: ['header', 'objId', 'parentId'],
  data() {
    return {
      dialog: {
        header: '',
        objId: 0,
        open: false,
      },
      menuOptions: [],
      visible: true,
      loading: false,
      formData: {
        parentId: null,
        reviewType: '',
        name: '',
        sort: 1,
        note: '',
        indexId: '',
        subjectClassification: [],
        reviewMenuType: '1',
        startReviewDate: '',
        endReviewDate: '',
        reviewMeetingDate: '',
        sysAttMainVo: {
          sysAttMainIds: [],
        },
      },
      dataOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10000,
        departmentName: '',
      },
      fileLists: [],
    };
  },
  computed: {
    rules() {
      const rules = {
        parentId: [{ required: true, message: '上级分组ID不能为空' }],
        name: [{ required: true, message: '分组名称不能为空' }],
        sort: [{ required: true, message: '显示排序不能为空' }],
        subjectClassification: [{ required: true, validator: (val) => val.length > 0, message: '学科分类不能为空' }],
        reviewType: [{ required: true, message: '评审业务类型不能为空' }],
        startReviewDate: [{ required: true, message: '专家评审开始时间不能为空' }],
        endReviewDate: [
          {
            required: true,
            message: '专家评审截止时间不能为空',
          },
          {
            validator: (val) => {
              if (val && this.formData.startReviewDate) {
                const startTime = new Date(this.formData.startReviewDate).getTime();
                const endTime = new Date(val).getTime();
                return startTime <= endTime;
              }
              return true;
            },
            message: '评审开始时间不能大于评审截止时间',
            type: 'error',
          },
        ],
      };
      // <!-- 选了“立项评审(4)”，会议时间非必填，其他都必填 rules -->
      if (this.formData.reviewType !== '4') {
        const obj = { reviewMeetingDate: [{ required: true, message: '评审会议时间不能为空' }] };
        Object.assign(rules, obj);
      }
      return rules;
    },
  },
  watch: {
    // objId: {
    //   immediate: true,
    //   handler(val) {
    //     if (val) {
    //       this.getObj(val);
    //     }
    //   }
    // },
    parentId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.formData.parentId = val;
        }
      },
    },
  },
  async created() {
    await this.getIndexList();
    if (this.objId !== 0) {
      this.getObj();
    }
  },
  methods: {
    getIndexList() {
      return this.$api.kjxm.review
        .indexList(this.queryParams)
        .then((res) => {
          this.dataOptions = res.rows.map((val) => ({ label: val.name, value: val.id }));
        })
        .catch((e) => {
          this.$message.error(e.toString());
        });
    },
    getObj() {
      this.$api.kjxm.review
        .teamGet(this.objId)
        .then((response) => {
          // 选中行排前面
          // this.formData.selectedRowKeys = [response.data.indexId];
          // const index = this.data.findIndex((val) => val.id === this.formData.selectedRowKeys[0]);
          // const newArr = this.data.splice(index,1);
          // this.data.unshift(newArr[0]);
          response.data.subjectClassification = response.data.subjectClassification
            ? response.data.subjectClassification.split(',').filter((item) => item !== '')
            : [];
          Object.assign(this.formData, response.data);
          if (!this.formData.sysAttMainVo) {
            this.formData.sysAttMainVo = {
              sysAttMainIds: [],
            };
          }
          getFiles(this.objId).then((res) => {
            this.fileLists = [];
            const ids = [];
            if (res.data && res.data.length) {
              res.data.forEach((item) => {
                if (item.moduleKey === 'lockModuleKey') {
                  ids.push(item.id);
                  this.fileLists.push({
                    name: item.fileName,
                    url: item.fullFilePath,
                    id: item.id,
                    filePath: item.filePath,
                  });
                }
              });
              this.formData.sysAttMainVo.sysAttMainIds = ids;
            }
          });
        })
        .catch((e) => {
          this.$message.error(e.toString());
        });
    },
    onSubmit() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.loading = true;
          if (this.objId !== 0) {
            if (this.objId === this.formData.parentId) {
              this.formData.parentId = 0;
            }
            this.$api.kjxm.review
              .teamUpdate({
                ...this.formData,
                subjectClassification: this.formData.subjectClassification?.join(','),
              })
              .then((response) => {
                this.$message.success('修改成功');
                this.$emit('reload');
                if (this.formData.reviewMenuType === '2') {
                  this.$emit('changeActived', this.objId);
                }
                this.$emit('update:visible', false);
                this.loading = false;
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.toString());
              });
          } else {
            let { parentId } = this.formData;
            if (!this.formData.parentId) {
              parentId = 0;
            }
            this.$api.kjxm.review
              .teamAdd({
                ...this.formData,
                parentId,
                subjectClassification: this.formData.subjectClassification.join(','),
              })
              .then((response) => {
                this.$message.success('新增成功');
                this.$emit('reload');
                if (this.formData.reviewMenuType === '2') {
                  this.$emit('changeActived', response.data.id);
                }
                this.$emit('update:visible', false);
                this.loading = false;
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.toString());
              });
          }
        }
      });
    },
    closeDialog() {
      this.$emit('update:visible', false);
    },
  },
};
</script>

<style scoped>
.overlay-options {
  display: inline-block;
  font-size: 20px;
}
</style>
